package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.template.AliyunOssTemplate;
import com.tanhua.commons.template.BaiduAipFaceTemplate;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.CommonLikeUser;
import com.tanhua.domain.mongo.UserLikeCount;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserInfoService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserApi userApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private BaiduAipFaceTemplate aipFaceTemplate;
    @Autowired
    private AliyunOssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;





    /**
     * 根据id查询userInfo
     */
    public ResponseEntity findUserInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, vo);

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        log.info("查询用户资料成功");
        return ResponseEntity.ok(vo);
    }

    /**
     * 保存userInfo
     */
    public ResponseEntity saveUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
        log.info("保存用户资料成功");
        return ResponseEntity.ok(null);
    }

    /**
     * 保存用户要头像
     */
    public ResponseEntity saveHeader(MultipartFile headPhoto, Long userId) throws IOException {
        //1. 人脸识别
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            ResponseEntity.status(401).body(ErrorResult.faceDetectFailed());
        }
        //2. 上传头像
        String url = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //3. 将头像url 保存进数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(url);
        userInfo.setCoverPic(url);
        userInfoApi.update(userInfo);
        log.info("用户头像保存成功");
        return ResponseEntity.ok(null);
    }

    /**
     * 用户通用设置 - 读取
     */
    public ResponseEntity findSettings() {
        User user = UserHolder.getUser();
        //设置id和phone
        SettingsVO vo = new SettingsVO();
        vo.setId(user.getId());
        vo.setPhone(user.getMobile());

        //查询strangerQuestion
        Question question = questionApi.findByUserId(user.getId());
        if (question != null) {
            vo.setStrangerQuestion(question.getTxt());
        }
        //查询通知设置
        Settings settingsDb = settingsApi.findByUserId(user.getId());
        if (settingsDb != null) {
            vo.setLikeNotification(settingsDb.getLikeNotification());
            vo.setPinglunNotification(settingsDb.getPinglunNotification());
            vo.setGonggaoNotification(settingsDb.getGonggaoNotification());
        } else {
            //如果没有查询到通知设置，默认开启所有通知
            vo.setLikeNotification(true);
            vo.setPinglunNotification(true);
            vo.setGonggaoNotification(true);
            //并更新数据库为该用户增加通知设置
            settingsDb = new Settings();
            settingsDb.setUserId(user.getId());
            settingsDb.setGonggaoNotification(true);
            settingsDb.setPinglunNotification(true);
            settingsDb.setLikeNotification(true);
            settingsApi.save(settingsDb);
        }
        return ResponseEntity.ok(vo);
    }

    /**
     * 用户设置陌生人问题-保存
     * @param content   问题内容
     */
    public ResponseEntity saveQuestions(String content) {
        User user = UserHolder.getUser();
        //先根据用户id查询是否设置了陌生人问题
        Question question = questionApi.findByUserId(user.getId());
        if (question != null) {
            //如果查询到了则更新问题内容
            question.setTxt(content);
            questionApi.update(question);
        } else {
            question = new Question();
            question.setUserId(user.getId());
            question.setTxt(content);
            questionApi.save(question);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 通知设置-修改保存
     */
    public ResponseEntity saveNotifications(Settings settings) {
        User user = UserHolder.getUser();
        //1. 查询该用户通知设置
        Settings settingsDb = settingsApi.findByUserId(user.getId());
        settings.setId(settingsDb.getId());
        settings.setUserId(user.getId());
        settingsApi.update(settings);
        return ResponseEntity.ok(null);
    }

    /**
     * 用户黑名单-翻页列表
     */
    public ResponseEntity findBlackList(Integer page, Integer pagesize) {
        User user = UserHolder.getUser();
        //根据用户id查询用户黑名单列表
        IPage<UserInfo> iPage =  blackListApi.findByUserId(page, pagesize, user.getId());
        PageResult vo = new PageResult();
        if (iPage != null) {
            vo.setItems(iPage.getRecords());
            vo.setCounts((int) iPage.getTotal());
            vo.setPages((int) iPage.getPages());
            vo.setPage(page);
            vo.setPagesize(pagesize);
        }
        return ResponseEntity.ok(vo);
    }

    /**
     * 黑名单移除
     */
    public ResponseEntity remove(Long blackUserId) {
        User user = UserHolder.getUser();
        blackListApi.remove(user.getId(), blackUserId);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号-发送验证码
     */
    public ResponseEntity sendVerificationCode() {
        User user = UserHolder.getUser();
        //测试code写死
        //发送验证码
        String code = "123456";
        //将code存入redis中
        redisTemplate.opsForValue().set("CODE_" + user.getMobile(), code, Duration.ofMinutes(5));
        log.info("修改手机号发送验证码成功，手机号：{}，验证码：{}",user.getMobile(), code);
        return ResponseEntity.ok(null);
    }

    /**
     * 校验验证码
     */
    public ResponseEntity checkVerificationCode(String verificationCode) {
        User user = UserHolder.getUser();
        //从redis中取出code校验
        String code = redisTemplate.opsForValue().get("CODE_" + user.getMobile());

        boolean valid = code != null && code.equals(verificationCode);
        if (valid) {
            log.info("修改手机号校验验证码成功");
            redisTemplate.delete("CODE_" + user.getMobile());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("verification", valid);
        return ResponseEntity.ok(result);
    }

    /**
     * 修改手机号-保存
     */
    public ResponseEntity savePhone(String phone) {
        User user = UserHolder.getUser();
        log.info("userHolder中得user:{}",user);
//        User user1 = new User();
//        user1.setId(user.getId());
//        user1.setMobile(phone);
        user.setMobile(phone);
        userApi.update(user);
        return ResponseEntity.ok(null);
    }

    /**
     * 互相喜欢、喜欢、粉丝-统计
     */
    public ResponseEntity userLikeCounts() {
        Long userId = UserHolder.getUser().getId();
        //UserLike 封装了互相喜欢、喜欢、粉丝的数量
        UserLikeCount userLikeCount = userLikeApi.findUserLikeCounts(userId);
        return ResponseEntity.ok(userLikeCount);
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * @param type 1 互相喜欢、 2喜欢、 3 粉丝、 4 谁看过我
     */
    public ResponseEntity userLikeList(Integer page, Integer pagesize, Integer type) {
        Long userId = UserHolder.getUser().getId();
        PageResult pageResult = userLikeApi.findUserLikeList(page, pagesize, type, userId);

        //转换vo
        List<CommonLikeUser> userLikeList = pageResult.getItems();
        List<CommonLikeUserVO> vos = new ArrayList<>();
        for (CommonLikeUser commonLikeUser : userLikeList) {
            CommonLikeUserVO vo = new CommonLikeUserVO();

            UserInfo userInfo = userInfoApi.findById(commonLikeUser.getTargetUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setMatchRate(commonLikeUser.getScore().intValue());
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }

    //粉丝-喜欢
    public ResponseEntity likeFan(Long targetUserId) {
        Long userId = UserHolder.getUser().getId();
        //1. 删除userLike中的粉丝关系
        userLikeApi.removeFan(userId, targetUserId);

        //2. 将粉丝添加为好友
        friendApi.addContact(userId, targetUserId);

        //3. 注册环信，正常报错，先不进行环信注册
//        huanXinTemplate.addContact(userId.toString(), targetUserId.toString());
        return ResponseEntity.ok(null);
    }

    /**
     * 用户对好友取消喜欢
     * @param targetUserId 好友id
     */
    public ResponseEntity removeLike(Long targetUserId) {
        Long userId = UserHolder.getUser().getId();
        //这里仅对双向好友实现删除，如果需要扩展，增加type
        Integer type = 1;
        userLikeApi.removeContact(userId, targetUserId, type);
        return ResponseEntity.ok(null);
    }


}
